package hu.crs.demobank.authorization;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Servlet Filter implementation class AccessBlocker
 */

@WebFilter("/function/*")
public class AccessBlocker implements Filter {

	Logger logger = Logger.getLogger(AccessBlocker.class);
    /**
     * Default constructor. 
     */
    public AccessBlocker() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpServletRequest tmpRequest = (HttpServletRequest) request;
		HttpSession session = tmpRequest.getSession();
		boolean sessionAvailable = isLoggedIn(session);
		if (!sessionAvailable) {
			logger.warn("No session was available. User logged out!");
			HttpServletResponse tmpResponse = (HttpServletResponse) response;
			tmpResponse.sendRedirect(tmpRequest.getContextPath());
			return;
		}
		
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	
	public boolean isLoggedIn(HttpSession session) {
		return (session.getAttribute("loggedIn")!=null) && Boolean.parseBoolean(session.getAttribute("loggedIn").toString());
	}
}
